'''
Created on 2012-9-12

@author: ljing
'''
import MySQLdb
import types
from WeiboClient import WeiboClient
from conf import *
from MySqlDBHandle import MySqlDBHandle

class City(WeiboClient):
    mAPI = 'common/get_city'
    mSQLStatement = "INSERT INTO LU_City (id, name, provinceID, LAST_UPDATE_TIMESTAMP) VALUES %s ON DUPLICATE KEY UPDATE LAST_UPDATE_TIMESTAMP = current_timestamp;"
    mSQLValueStatement = "(%s, '%s', %s, current_timestamp),"

    def __init__(self, iProvinceID):
        self.mProvinceID = iProvinceID
        WeiboClient.__init__(self)
        
    def  process(self):
        iParams = {}
        iParams['province'] = self.mProvinceID
        iParams['access_token'] = self.mPublicToken[1]
#        iParams['access_token'] = PublicToken.getPublicToken()[0]
        lJsonResult = self.fetchUsingAPI(self.mAPI, iParams)
        self.mJsonData = lJsonResult
        if type(self.mJsonData) == types.ListType and len(self.mJsonData)>0:
            self._InsertCityToDB() 



    def _InsertCityToDB(self):
        assert(type(self.mJsonData) == types.ListType)
        lValueStatement = ""
        for  lSingleData in self.mJsonData:
            (lCityId, lCityName) = lSingleData.items()[0]
            lValueStatement += (self.mSQLValueStatement % (lCityId, lCityName, self.mProvinceID))
        lSQLStatement = self.mSQLStatement % lValueStatement[:len(lValueStatement) - 1]
        try:
            MySqlDBHandle.execSqlStatement(lSQLStatement)
        except Exception, e:
            print "Error when insert city into LU_City "
